<?php if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Auth extends CI_Controller {

  function __construct() {
    parent::__construct();
    $this->load->library('form_validation');
    $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
    $this->lang->load('auth');
    $this->load->helper('language');
  }

  function index() {

    //jika tidak login, redirect ke halaman login
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
      show_404();
      //jika syarat terpenuhi, menuju ke halaman auth
    } else {
      //title
      $judul = 'Daftar Pengguna';
      $this->data['judul'] = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb($judul);

      $this->load->model('m_auth');

      //list of users
      if (!$this->ion_auth->in_group($this->config->item('super_admin_group', 'ion_auth'))) {
        $this->data['users'] = $this->m_auth->get_users_not_sa()->result();
        foreach ($this->data['users'] as $k => $user) {
          $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
        }
      } else {
        $this->data['users'] = $this->ion_auth->users()->result();
        foreach ($this->data['users'] as $k => $user) {
          $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
        }
      }

      //menggunakan theme back
      $this->layout->theme('apotek','auth/index', $this->data);
    }
  }

  //deactivate the user
  function deactivate($id = NULL) {   

    $this->load->helper('cek_id');
    if(!cek_id($id, 'id', $this->tables['users'])){
      show_404();
    }

    $id = (int) $id;

    $this->load->library('form_validation');
    $this->form_validation->set_rules('confirm', 'Konfirmasi', 'required');
    $this->form_validation->set_rules('id', 'ID Pengguna', 'required|alpha_numeric');

    if ($this->form_validation->run() == FALSE) {
      $this->data['user'] = $this->ion_auth->user($id)->row();

      //title
      $judul = 'Non-Aktifkan <font color="#38A58E" data-toggle="tooltip" data-placement="top" title="Email: ' .$this->data['user']->email . ' Username: ' .$this->data['user']->username . '">' . $this->data['user']->first_name. ' ' .$this->data['user']->last_name . '</font>' . '';
      $this->data['judul'] = $judul;
      $this->layout->set_title('Non-Aktifkan ' . $this->data['user']->first_name. ' ' .$this->data['user']->last_name);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Pengguna', site_url('auth'));
      $this->breadcrumb->add_crumb($judul);

      $this->layout->theme('apotek','auth/deactivate_user', $this->data);
    } else {
      // do we really want to deactivate?
      if ($this->input->post('confirm') == 'yes') {
        // do we have a valid request?
        if ($id != $this->input->post('id')) {
          show_404();
        }

        // do we have the right userlevel?
        if ($this->ion_auth->logged_in() && $this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
          $this->ion_auth->deactivate($id);
        }
      }
      //redirect them back to the auth page
      redirect('auth', 'refresh');
    }
  }

    //activate the user
  function activate($id, $code = false) {

    $this->load->helper('cek_id');
    if(!cek_id($id, 'id', $this->tables['users'])){
      set_flash('danger','Ups, pengguna tidak terdaftar');
      redirect("auth", 'refresh');
    }

    if ($code !== false) {
      $activation = $this->ion_auth->activate($id, $code);
    } else if ($this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
      $activation = $this->ion_auth->activate($id);
    }

    if ($activation) {
      //redirect them to the auth page
      redirect("auth", 'refresh');
    } else {
      //redirect them to the forgot password page
      redirect("auth/forgot_password", 'refresh');
    }
  }

  //edit a user
  function edit_user($id) {

    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth'))) && !($this->ion_auth->user()->row()->id == $id)) {
      show_404();
    }elseif (isset($_POST) && !empty($_POST)) {

      $user = $this->ion_auth->user($id)->row();

      //validate form input
      $this->form_validation->set_rules('first_name', 'Nama Depan', 'required|xss_clean');
      $this->form_validation->set_rules('nickname', 'Nama Panggilan', 'required|xss_clean');
      $this->form_validation->set_rules('phone', 'Telepon', 'required|xss_clean');
      $this->form_validation->set_rules('username', 'Nama Pengguna', 'required|callback_username_update_check_b[username]|xss_clean');
      $this->form_validation->set_rules('email', 'Email', 'callback_email_update_check_b|xss_clean');
      $this->form_validation->set_rules('company', 'Perusahaan', 'required|xss_clean');
      $this->form_validation->set_rules('groups', 'Grup', 'xss_clean');

      //update the password if it was posted
      if ($this->input->post('password')) {
        $this->form_validation->set_rules('password', 'Kata Sandi', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
        $this->form_validation->set_rules('password_confirm', 'Konfirmasi Kata Sandi', 'required');
      }

      if ($this->form_validation->run() === TRUE) {
        $data = array('first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'nickname' => $this->input->post('nickname'), 'username' => strtolower($this->input->post('username')), 'email' => strtolower($this->input->post('email')), 'company' => $this->input->post('company'), 'phone' => $this->input->post('phone'));

        //update the password if it was posted
        if ($this->input->post('password')) {
          $data['password'] = $this->input->post('password');
        }

        // Only allow updating groups if user is admin or super_admin
        if ($this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {

          //Update the groups user belongs to
          $groupData = $this->input->post('groups');

          if (isset($groupData) && !empty($groupData)) {

            $this->ion_auth->remove_from_group('', $id);

            foreach ($groupData as $grp) {
              $this->ion_auth->add_to_group($grp, $id);
            }
            $ok = 'okeh';
          } else {
            $ok = 'noh';
          }
        }

        //check to see if we are updating the user
        if ($this->ion_auth->update($user->id, $data) && $ok == 'okeh') {
          //redirect them back to the admin page if admin, or to the base url if non admin
          if ($this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
            redirect('auth', 'refresh');
          } else {
            redirect('/', 'refresh');
          }
        } else {
          //redirect them back to the admin page if admin, or to the base url if non admin
          if ($this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
            redirect('auth', 'refresh');
          } else {
            redirect('/', 'refresh');
          }
        }
      }else{
        //display the edit user form
        $err  = array(
          str_replace(array('<p>','</p>'), '', form_error('first_name')),
          str_replace(array('<p>','</p>'), '', form_error('nickname')),
          str_replace(array('<p>','</p>'), '', form_error('phone')),
          str_replace(array('<p>','</p>'), '', form_error('username')),
          str_replace(array('<p>','</p>'), '', form_error('email')),
          str_replace(array('<p>','</p>'), '', form_error('company')),
          str_replace(array('<p>','</p>'), '', form_error('groups')),
          str_replace(array('<p>','</p>'), '', form_error('password')),
          str_replace(array('<p>','</p>'), '', form_error('password_confirm')),
                );
        set_flash('danger', array_diff($err, array('')));
      
        redirect('auth/edit_user/' . $id);
      }
    }else{

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['users'])){
        set_flash('danger', 'Ups, Pengguna tidak terdaftar');
        redirect('auth');       
      }

      $this->load->model('m_auth');

      $user = $this->ion_auth->user($id)->row();
      if (!$this->ion_auth->in_group($this->config->item('super_admin_group', 'ion_auth'))) {
        $groups = $this->m_auth->get_groups_only_and_where_not_sa()->result_array();
      } else {
        $groups = $this->ion_auth->groups()->result_array();
      }
      $currentGroups = $this->ion_auth->get_users_groups($id)->result();  

      // Title
      $judul = 'Edit Pengguna';
      $this->data['judul'] = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Pengguna', site_url('auth'));
      $this->breadcrumb->add_crumb($judul);

      //display the edit user form
      //pass the user to the view
      $this->data['user'] = $user;
      $this->data['groups'] = $groups;
      $this->data['currentGroups'] = $currentGroups;

      $this->data['first_name'] = array('name' => 'first_name', 'id' => 'first_name', 'type' => 'text', 'value' => $this->form_validation->set_value('first_name', $user->first_name), 'class' => 'form-control input-sm', 'placeholder' => '');
      $this->data['last_name'] = array('name' => 'last_name', 'id' => 'last_name', 'type' => 'text', 'value' => $user->last_name, 'class' => 'form-control input-sm', 'placeholder' => '');
      $this->data['nickname'] = array('name' => 'nickname', 'id' => 'nickname', 'type' => 'text', 'value' => $this->form_validation->set_value('nickname', $user->nickname), 'class' => 'form-control input-sm', 'placeholder' => '');
      $this->data['username'] = array('name' => 'username', 'id' => 'username', 'type' => 'text', 'value' => $this->form_validation->set_value('username', $user->username), 'class' => 'form-control input-sm', 'placeholder' => '');
      $this->data['email'] = array('name' => 'email', 'id' => 'email', 'type' => 'text', 'value' => $this->form_validation->set_value('email', $user->email), 'class' => 'form-control input-sm', 'placeholder' => '');
      $this->data['company'] = array('name' => 'company', 'id' => 'company', 'type' => 'hidden', 'value' => '-', 'class' => 'form-control input-sm', 'placeholder' => 'Nama Perusahaan');
      $this->data['phone'] = array('name' => 'phone', 'id' => 'phone', 'type' => 'hidden', 'value' => '-', 'class' => 'form-control input-sm', 'placeholder' => 'Telepon');
      $this->data['password'] = array('name' => 'password', 'id' => 'password', 'type' => 'password', 'class' => 'form-control input-sm', 'placeholder' => 'Tetap kosongkan jika tidak diganti');
      $this->data['password_confirm'] = array('name' => 'password_confirm', 'id' => 'password_confirm', 'type' => 'password', 'class' => 'form-control input-sm', 'placeholder' => 'Konfirmasi Sandi');

      $this->layout->theme('apotek','auth/edit_user', $this->data);
    }
  }

  //create a new user
  function create_user() {

    //jika tidak login, redirect ke halaman login
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
      show_404();
    }elseif (isset($_POST) && !empty($_POST)) {

      $tables = $this->config->item('tables', 'ion_auth');

      //validate form input
      $this->form_validation->set_rules('first_name', 'Nama Depan', 'required|xss_clean');   
      $this->form_validation->set_rules('username', 'Nama Pengguna', 'required|is_unique[' . $tables['users'] . '.username]');
      $this->form_validation->set_rules('nickname', 'Nama Panggilan', 'required|xss_clean');
      $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[' . $tables['users'] . '.email]');
      $this->form_validation->set_rules('password', 'Kata Sandi', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
      $this->form_validation->set_rules('password_confirm', 'Konfirmasi Kata Sandi', 'required');

      if ($this->form_validation->run() == true) {

        $username = strtolower($this->input->post('username'));
        $email = strtolower($this->input->post('email'));
        $password = $this->input->post('password');
        $additional_data = array('first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'nickname' => $this->input->post('nickname'), 'company' => '-', 'phone' => '-');

        if($this->ion_auth->register($username, $password, $email, $additional_data)){
          set_flash('success', 'Akun <strong>' .  $this->input->post('first_name') . ' ' .  $this->input->post('last_name') . '</strong> dengan email ' . $this->input->post('email') . ' berhasil dibuat');
          redirect("auth", 'refresh');
        }else{
          // set_flash untuk gagal register/danger ngambil dari model
          redirect("auth", 'refresh');
        }     
      
      }else{

        //set the flash data error message if there is one
        $err  = array(
          str_replace(array('<p>','</p>'), '', form_error('first_name')),
          str_replace(array('<p>','</p>'), '', form_error('nickname')),
          str_replace(array('<p>','</p>'), '', form_error('username')),
          str_replace(array('<p>','</p>'), '', form_error('email')),
          str_replace(array('<p>','</p>'), '', form_error('password')),
          str_replace(array('<p>','</p>'), '', form_error('password_confirm')),
                  );
        set_flash('danger', array_diff($err, array('')));
        redirect('auth/create_user');

      }

    }else{

      // title
      $judul = 'Tambah Pengguna';
      $this->data['judul'] = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Pengguna', site_url('auth'));
      $this->breadcrumb->add_crumb($judul);

      //display the create user form
      $this->data['first_name'] = array('name' => 'first_name', 'id' => 'first_name', 'type' => 'text', 'value' => $this->form_validation->set_value('first_name'), 'class' => 'form-control input-sm', 'placeholder' => 'Nama Depan');
      $this->data['last_name'] = array('name' => 'last_name', 'id' => 'last_name', 'type' => 'text', 'class' => 'form-control input-sm', 'placeholder' => 'Nama Belakang');
      $this->data['nickname'] = array('name' => 'nickname', 'id' => 'nickname', 'type' => 'text', 'value' => $this->form_validation->set_value('nickname'), 'class' => 'form-control input-sm', 'placeholder' => 'Nama Panggilan');
      $this->data['username'] = array('name' => 'username', 'id' => 'username', 'type' => 'text', 'value' => $this->form_validation->set_value('username'), 'class' => 'form-control input-sm', 'placeholder' => 'Nama Pengguna');
      $this->data['email'] = array('name' => 'email', 'id' => 'email', 'type' => 'text', 'value' => $this->form_validation->set_value('email'), 'class' => 'form-control input-sm', 'placeholder' => 'Email');
      $this->data['password'] = array('name' => 'password', 'id' => 'password', 'type' => 'password', 'value' => $this->form_validation->set_value('password'), 'class' => 'form-control input-sm', 'placeholder' => 'Kata Sandi');
      $this->data['password_confirm'] = array('name' => 'password_confirm', 'id' => 'password_confirm', 'type' => 'password', 'value' => $this->form_validation->set_value('password_confirm'), 'class' => 'form-control input-sm', 'placeholder' => 'Konfirmasi Kata Sandi');

      $this->layout->theme('apotek','auth/create_user', $this->data);
    }
  }

  //delete a user
  function delete_user($id) {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

      //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth'))) && !($this->ion_auth->user()->row()->id == $id)) {
      show_404();
    }

    $this->load->helper('cek_id');
    if(!cek_id($id, 'id', $this->tables['users'])){
      set_flash('danger', 'Ups, Pengguna tidak terdaftar');
      redirect('auth');       
    }

    // $this->load->model('m_auth');
    $this->ion_auth->delete_user($id);
    redirect('auth');
  }

  //grup pengguna
  function groups() {

    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
      show_404();
    } else {

      $this->load->model('m_auth');
      $this->load->helper('multi_in_array');
      if (!$this->ion_auth->in_group($this->config->item('super_admin_group', 'ion_auth'))) {
        $this->data['list'] = $this->m_auth->get_groups_not_sa();
      } else {
        $this->data['list'] = $this->m_auth->get_groups_all();
      }

      //title
      $judul = 'Grup Pengguna';
      $this->data['judul'] = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Grup Pengguna');

      $this->layout->theme('apotek','auth/groups', $this->data);
    }
  }

  // create a new group
  function create_group() {

    //jika tidak login, redirect ke halaman login
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
      show_404();
    } elseif (isset($_POST) && !empty($_POST)) {

      //validate form input
      $this->form_validation->set_rules('group_name', 'Nama Grup', 'required|alpha_dash|xss_clean');
      $this->form_validation->set_rules('description', 'Deskripsi Grup', 'xss_clean');

      if ($this->form_validation->run() == TRUE) {
        $new_group_id = $this->ion_auth->create_group(strtolower($this->input->post('group_name')), $this->input->post('description'));

        if ($new_group_id) {

          $jml = $this->input->post('jml');
          for ($i=1; $i <= $jml; $i++) { 
            $role = $this->input->post('roles' . $i);
            if(!$this->input->post('c' . $i)){
              $c = 0;
            }else{
              $c = 1;
            }

            if(!$this->input->post('r' . $i)){
              $r = 0;
            }else{
              $r = 1;
            }

            if(!$this->input->post('u' . $i)){
              $u = 0;
            }else{
              $u = 1;
            }

            if(!$this->input->post('d' . $i)){
              $d = 0;
            }else{
              $d = 1;
            }

            if(!empty($role)){
              $dataInsert = array('group_id' => $new_group_id, 'role_id' => $role, 'rule' => $c . $r . $u . $d);
              $this->load->model('m_auth');
              $sukses = $this->m_auth->insert_groups_role($dataInsert);
            }
            
          }

          set_flash('success', 'Grup ' . $this->input->post('group_name') . ' berhasil dibuat');
          redirect("auth/groups", 'refresh');
        }else{
          redirect("auth/groups", 'refresh');
        }

      }else{
        $err  = array(
          str_replace(array('<p>','</p>'), '', form_error('group_name')),
          str_replace(array('<p>','</p>'), '', form_error('description')),
                  );
        set_flash('danger', array_diff($err, array('')));
        redirect("auth/create_group", 'refresh');
      } 

    } else {

      // title
      $judul                = "Tambah Grup";
      $this->data['judul']  = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Grup', site_url('auth/groups'));
      $this->breadcrumb->add_crumb('Tambah Grup');

      $this->load->model('m_auth');
      $this->data['roles'] = $this->m_auth->get_roles();

      $this->data['group_name'] = array('name' => 'group_name', 'id' => 'group_name', 'type' => 'text', 'value' => $this->form_validation->set_value('group_name'), 'class' => 'form-control input-sm', 'placeholder' => 'Nama Grup');
      $this->data['description'] = array('name' => 'description', 'id' => 'description', 'type' => 'text', 'value' => $this->form_validation->set_value('description'), 'class' => 'form-control input-sm', 'placeholder' => 'Deskripsi Grup');

      $this->layout->theme('apotek','auth/create_group', $this->data);

    }

    
  }

  //edit a group
  function edit_group($id) {

    //jika tidak login, redirect ke halaman login
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

      //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth'))) || !$id || empty($id)) {
      show_404();
    } elseif (isset($_POST) && !empty($_POST)) {

        $this->load->model('m_auth');

        //validate form input
        $this->form_validation->set_rules('group_name', 'Nama grup', 'required|alpha_dash|xss_clean');
        $this->form_validation->set_rules('group_description', 'Deskripsi grup', 'xss_clean');
        $this->form_validation->set_rules('roles', 'Role Grup', 'xss_clean');

        if ($this->form_validation->run() === TRUE) {

        //update grup
        $dataUpdate = array('name' => $this->input->post('group_name'), 'description' => $this->input->post('group_description'));
        $group_update = $this->m_auth->update_group($id, $dataUpdate);

        if ($group_update) {
          $delete_groups_role = $this->m_auth->delete_groups_role($id);
        }

        // echo "<pre>";
        $roles = $this->input->post('roles');
        $c = $this->input->post('c');
        $r = $this->input->post('r');
        $u = $this->input->post('u');
        $d = $this->input->post('d');

        if ($roles > 0) {
          foreach ($roles as $key => $value) {
            $roles_rules[$key] = array('role_id' => $value, 'c' => $c[$key], 'r' => $r[$key], 'd' => $d[$key], 'u' => $u[$key]);
          }
        }

        if (isset($roles_rules) && !empty($roles_rules)) {
          if ($delete_groups_role) {
            foreach ($roles_rules as $role_and_rule) {
              $dataInsert = array('group_id' => $id, 'role_id' => $role_and_rule['role_id'], 'rule' => $role_and_rule['c'] . $role_and_rule['r'] . $role_and_rule['u'] . $role_and_rule['d']);
              $sukses = $this->m_auth->insert_groups_role($dataInsert);
            }
          }
        }
        else {
          $sukses = $group_update;
        }

        if ($sukses) {
          set_flash('success', 'Grup <strong>' . $this->input->post('group_name') . '</strong> berhasil diperbaharui');
        } else {
          set_flash('danger', 'Grup <strong>' . $this->input->post('group_name') . '</strong> gagal diperbaharui');
        }
        redirect("auth/groups", 'refresh');
      }else{

        $err  = array(
          str_replace(array('<p>','</p>'), '', form_error('group_name')),
          str_replace(array('<p>','</p>'), '', form_error('group_description')),
                  );
        set_flash('danger', array_diff($err, array('')));
        redirect('auth/edit_group/' . $id, 'refresh');

      }

    } else{

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['groups'])){
        set_flash('danger', 'Ups, Grup tidak tersedia');
        redirect('auth/groups');
      }elseif($this->cek_group_id($id)){
        set_flash('danger', 'Ups, Grup tidak boleh diedit');
        redirect('auth/groups');
      }

      //title
      $judul                = 'Edit Grup Pengguna';
      $this->data['judul']  = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Grup', site_url('auth/groups'));
      $this->breadcrumb->add_crumb('Edit Grup Pengguna');

      $this->load->model('m_auth');
      $group = $this->ion_auth->group($id)->row();
      $roles = $this->m_auth->get_roles();
      $currentRoles = $this->m_auth->get_permissions_by_group_id($id);

      //pass the user to the view
      $this->data['group'] = $group;
      $this->data['roles'] = $roles;
      $this->data['currentRoles'] = $currentRoles;

      $this->data['group_name'] = array('name' => 'name', 'id' => 'name', 'type' => 'text', 'value' => $this->form_validation->set_value('group_name', ucwords(str_replace('_', ' ', $group->name))), 'class' => 'form-control input-sm', 'placeholder' => 'Nama Grup', 'readonly' => 'readonly');
      $this->data['group_name_hide'] = array('name' => 'group_name', 'id' => 'group_name', 'type' => 'hidden', 'value' => $this->form_validation->set_value('group_name', $group->name), 'class' => 'form-control input-sm', 'placeholder' => 'Nama Grup', 'readonly' => 'readonly');
      $this->data['group_description'] = array('name' => 'group_description', 'id' => 'group_description', 'type' => 'text', 'value' => $this->form_validation->set_value('group_description', $group->description), 'class' => 'form-control input-sm', 'placeholder' => 'Deskripsi Grup');

      $this->layout->theme('apotek','auth/edit_group', $this->data);

    }
  }

  //delete a group
  function delete_group($id) {

    //jika tidak login, redirect ke halaman login
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth'))) || !$id || empty($id)) {
      show_404();
    } else {

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['groups'])){
        set_flash('danger', 'Ups, Grup tidak tersedia');
        redirect('auth/groups');        
      }

      $this->ion_auth->delete_group($id);
      redirect('auth/groups');

    }
    
  }

  //role
  function roles() {

    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth')))) {
      show_404();
    } else {

      $this->load->helper('trim_text');
      $this->load->model('m_auth');
      $this->data['list'] = $this->m_auth->get_roles();

      // title
      $judul                = 'Role';
      $this->data['judul']  = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Role');

      $this->layout->theme('apotek','auth/roles', $this->data);
    }
  }

  // create a new role
  function create_role() {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth')))) {
      show_404();
    } elseif (isset($_POST) && !empty($_POST)) {
      $this->load->model('m_auth');

      //validate form input
      $this->form_validation->set_rules('ordinal_number', 'Urutan', 'required|numeric|xss_clean');
      $this->form_validation->set_rules('role_name', 'Nama Role Grup', 'required|xss_clean');
      $this->form_validation->set_rules('role_url', 'URL Role Grup', 'is_unique[' . $this->tables['roles'] . '.url]|required|xss_clean');
      $this->form_validation->set_rules('role_desc', 'Deskripsi Role Grup', 'xss_clean');

      if ($this->form_validation->run() == TRUE) {
        $dataInsert = array('name' => $this->input->post('role_name'), 'ordinal_number' => $this->input->post('ordinal_number'), 'category_id' => $this->input->post('kat'), 'url' => strtolower($this->input->post('role_url')), 'desc' => $this->input->post('role_desc'), 'parent' => $this->input->post('parent'));
        $new_role_id = $this->m_auth->create_role($dataInsert);

        if ($new_role_id) {
          set_flash('success', 'Role <strong>' . $this->input->post('role_name') . '</strong> berhasil ditambahkan');
          redirect('auth/roles', 'refresh');
        }
      } else {

        $err  = array(
          str_replace(array('<p>','</p>'), '', form_error('ordinal_number')),
          str_replace(array('<p>','</p>'), '', form_error('role_name')),
          str_replace(array('<p>','</p>'), '', form_error('role_url')),
          str_replace(array('<p>','</p>'), '', form_error('role_desc')),
                  );
        set_flash('danger', array_diff($err, array('')));
        redirect('auth/create_role', 'refresh');

      }
        
    }else{

      //title
      $judul                = 'Tambah Role';
      $this->data['judul']  = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Role', site_url('auth/roles'));
      $this->breadcrumb->add_crumb($judul);

      //roles category
      $this->load->model('m_auth');
      $this->data['roles_cat'] = $this->m_auth->get_roles_category();

      $this->layout->theme('apotek','auth/create_role', $this->data);

    }
  }

  function edit_role($id = '') {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'))) || !$id || empty($id)) {
      show_404();
    } else {

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['roles'])){
        set_flash('danger', 'Ups, Role tidak tersedia');
        redirect('auth/roles');       
      }

      // title
      $judul                = 'Edit Role';
      $data['judul']  = $judul;
      $this->layout->set_title($judul);

      $this->load->model('m_auth');     

      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Role', site_url('auth/roles'));
      $this->breadcrumb->add_crumb($judul);

      $data['roles_cat']    = $this->m_auth->get_roles_category();
      $data['role']         = $this->m_auth->get_role_by_id($id);

      $this->layout->theme('apotek','auth/edit_role', $data);
    }
  }

  function update_role() {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth')))) {
      show_404();
    } else {
      //load model
      $this->load->model('m_auth');

      //untuk cek unique update
      $params = array($id = $this->input->post('id'), $url = $this->input->post('role_url'));
      $sql = 'SELECT url FROM ' . $this->tables['roles'] . ' WHERE id != ? AND url = ?';
      $query = $this->db->query($sql, $params);

      //validate form input
      $this->form_validation->set_rules('ordinal_number', 'Urutan', 'required|numeric|xss_clean');
      $this->form_validation->set_rules('role_name', 'Nama Role Grup', 'required|xss_clean');
      $this->form_validation->set_rules('role_url', 'URL Role Grup', 'required|xss_clean');
      $this->form_validation->set_rules('role_desc', 'Deskripsi Role Grup', 'xss_clean');

      //jika validasi berjalan
      if ($this->form_validation->run() == FALSE) {

        //semua error validasi ditampung kedalam flashdata
        $err  = array(
          str_replace(array('<p>','</p>'), '', form_error('ordinal_number')),
          str_replace(array('<p>','</p>'), '', form_error('role_name')),
          str_replace(array('<p>','</p>'), '', form_error('role_url')),
          str_replace(array('<p>','</p>'), '', form_error('role_desc')),
                );
        set_flash('danger', array_diff($err, array('')));
        redirect('auth/edit_role/' . $this->input->post('id'));

        //jika dalam tabel roles terdapat url yang sama dengan url yang ber-id selian dengan id role ini

      } elseif ($query->num_rows() > 0) {
        $url_exist = $this->input->post('role_url');
        set_flash('danger', 'Controller ' . $url_exist . ' telah digunakan, coba ganti yang lain');   redirect('auth/edit_role/' . $id);

      //jika tidak ada masalah, update data
      } else {
        $dataUpdate = array('name' => $this->input->post('role_name'), 'category_id' => $this->input->post('category_id'), 'url' => strtolower($this->input->post('role_url')), 'desc' => $this->input->post('role_desc'), 'ordinal_number' => $this->input->post('ordinal_number'), 'parent' => $this->input->post('parent'));
        $updateRole = $this->m_auth->update_role($id, $dataUpdate);

        //jika berhasil update
        if ($updateRole) {
          set_flash('success', 'Role <strong>' . $this->input->post('role_name') . '</strong> berhasil diperbaharui');
          redirect("auth/roles", 'refresh');

        //jika gagal update
        } else {
          set_flash('danger', 'Role <strong>' . $this->input->post('role_name') . '</strong> gagal diperbaharui');
          redirect('auth/roles');
        }
      }
    }
  }

  //delete a role
  function delete_role($id) {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'))) || !$id || empty($id)) {
      show_404();
    } else {

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['roles'])){
        set_flash('danger', 'Ups, Role tidak tersedia');
        redirect('auth/roles');       
      }

      $this->load->model('m_auth');
      if ($this->m_auth->delete_role($id)) {
        set_flash('success', 'Role berhasil dihapus');
      } else {
        set_flash('danger', 'Role gagal dihapus');
      }
      redirect('auth/roles');

    }   
  }

    //roles category
  function roles_category() {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth')))) {
      show_404();
    } else {

      $judul                = 'Kategori Role';
      $this->data['judul']  = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb($judul);

      $this->load->helper('multi_in_array');
      $this->load->model('m_auth');

      $this->data['roles_cat']    = $this->m_auth->get_roles_category();
      $this->data['roles_cat_id'] = $this->m_auth->get_roles_cat_id_at_roles();

      $this->layout->theme('apotek','auth/roles_category', $this->data);
    }
  }

  // create role category
  function create_roles_category() {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth')))) {
      show_404();
    } elseif ((isset($_POST) && !empty($_POST))) {
      
      $this->load->model('m_auth');

      //validate form input
      $this->form_validation->set_rules('ordinal_number', 'Urutan', 'numeric|required|xss_clean');
      $this->form_validation->set_rules('category', 'Kategori Role', 'is_unique[' . $this->tables['roles_category'] . '.category]|required|xss_clean');

      if ($this->form_validation->run() == TRUE) {
        $dataInsert = array('category' => $this->input->post('category'), 'icon_code' => $this->input->post('icon_code'), 'ordinal_number' => $this->input->post('ordinal_number'));
        $new_cat_id = $this->m_auth->create_roles_category($dataInsert);

        if ($new_cat_id) {
          set_flash('success', 'Kategori Role <strong>' . $this->input->post('category') . '</strong> berhasil ditambahkan');
          redirect("auth/roles_category", 'refresh');
        }else{
          set_flash('danger', 'Kategori Role <strong>' . $this->input->post('category') . '</strong> gagal ditambahkan');
          redirect("auth/roles_category", 'refresh');
        }
      }else{
        $err  = array(
                  str_replace(array('<p>','</p>'), '', form_error('ordinal_number')),
                  str_replace(array('<p>','</p>'), '', form_error('category')),
                );
        set_flash('danger', array_diff($err, array('')));
        redirect("auth/create_roles_category", 'refresh');
      }
    } else {

      //title
      $judul                          = 'Tambah Kategori Role';
      $this->data['judul']            = $judul;
      $this->layout->set_title($judul);

      //breadcrumb
      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Kategori Role', site_url('auth/roles_category'));
      $this->breadcrumb->add_crumb($judul);

      $this->layout->theme('apotek','auth/create_roles_category', $this->data);

    }
  }

  //edit role category
  function edit_roles_category($id = '') {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'))) || !$id || empty($id)) {
      show_404();
    } else {

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['roles_category'])){
        set_flash('danger', 'Ups, Kategori Role tidak tersedia');
        redirect('auth/roles_category');        
      }

      $judul            = 'Edit Kategori Role';
      $data['judul']    = $judul;     
      $this->layout->set_title($judul);

      $this->load->library('breadcrumb');
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Autentikasi', site_url('auth'));
      $this->breadcrumb->add_crumb('Kategori Role', site_url('auth/roles_category'));
      $this->breadcrumb->add_crumb($judul);

      $this->load->model('m_auth');
      $data['role_cat'] = $this->m_auth->get_role_cat_by($id);
      $this->layout->theme('apotek','auth/edit_roles_category', $data);
    }
  }

  //edit kategori role
  function update_roles_category() {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

    //jika tidak termasuk grup admin atau super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth')))) {
      show_404();
    } else {

      //load model
      $this->load->model('m_auth');

      //untuk cek unique update
      $params = array($id = $this->input->post('id'), $url = $this->input->post('category'));
      $sql = 'SELECT category FROM ' . $this->tables['roles_category'] . ' WHERE id != ? AND category = ?';
      $query = $this->db->query($sql, $params);
      
      if (!$id || empty($id)) {
        redirect('auth/roles', 'refresh');
      } else {

        //validate form input
        $this->form_validation->set_rules('ordinal_number', 'Urutan', 'required|numeric|xss_clean');
        $this->form_validation->set_rules('category', 'Kategori Role', 'required|xss_clean');

        //jika validasi berjalan
        if ($this->form_validation->run() == FALSE) {

          $err  = array(
              str_replace(array('<p>','</p>'), '', form_error('ordinal_number')),
              str_replace(array('<p>','</p>'), '', form_error('category')),
            );
          set_flash('danger', array_diff($err, array('')));
          redirect('auth/edit_roles_cat/' . $id);

        } elseif ($query->num_rows() > 0) {
          $cat_exist = $this->input->post('category');
          set_flash('danger', 'Kategori Role ' . $cat_exist . ' telah digunakan, coba ganti yang lain');
          redirect('auth/edit_roles_cat/' . $id);

          //jika tidak ada masalah, update data
        } else {
          $dataUpdate = array('category' => $this->input->post('category'), 'icon_code' => $this->input->post('icon_code'), 'ordinal_number' => $this->input->post('ordinal_number'));
          $updateCatRole = $this->m_auth->update_roles_category($id, $dataUpdate);

          //jika berhasil update
          if ($updateCatRole) {
            set_flash('success', 'Kategori Role <strong>' . $this->input->post('category') . '</strong> berhasil diperbaharui');
            redirect("auth/roles_category", 'refresh');

            //jika gagal update
          } else {
            set_flash('danger', 'Kategori Role gagal diperbaharui');
            redirect('auth/roles_category');
          }
        }
      }
    }
  }

  //delete a roles category
  function delete_roles_category($id) {

    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');

      //jika tidak termasuk grup super_admin
    } elseif (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'))) || !$id || empty($id)) {
      show_404();
    }else{

      $this->load->helper('cek_id');
      if(!cek_id($id, 'id', $this->tables['roles_category'])){
        set_flash('danger', 'Ups, Kategori Role tidak tersedia');
        redirect('auth/roles_category');        
      }

      $this->load->model('m_auth');
      if ($this->m_auth->delete_roles_category($id)) {
        set_flash('success', 'Kategori Role berhasil dihapus');
      } else {
        set_flash('danger', 'Role gagal dihapus');
      }
      redirect('auth/roles_category');  

    }
    
  }

  function me() {
    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');
    } else {
      
      //jika update
      if (isset($_POST) && !empty($_POST)) {

        //validate form input
        $this->form_validation->set_rules('first_name', 'Nama Depan', 'required|xss_clean');
        $this->form_validation->set_rules('last_name', 'Nama Belakang', 'required|xss_clean');
        $this->form_validation->set_rules('nickname', 'Nama Panggilan', 'required|xss_clean');
        $this->form_validation->set_rules('username', 'Nama Pengguna', 'required|alpha_numeric|xss_clean|callback_username_update_check');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|callback_email_update_check');

        if ($this->form_validation->run() === TRUE) {
          $data = array('first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'nickname' => $this->input->post('nickname'), 'username' => strtolower($this->input->post('username')), 'email' => strtolower($this->input->post('email')), 'phone' => $this->input->post('phone'));

          if ($this->ion_auth->update(user_id(), $data)) {
            set_flash('success', 'Profil Anda berhasil diperbaharui');
            redirect('me', 'refresh');
          } else {

            set_flash('danger', 'Profil Anda gagal diperbaharui');
            redirect('me', 'refresh');
          }
        }else{
        	$err  = array(
              str_replace(array('<p>','</p>'), '', form_error('first_name')),
              str_replace(array('<p>','</p>'), '', form_error('last_name')),
              str_replace(array('<p>','</p>'), '', form_error('nickname')),
              str_replace(array('<p>','</p>'), '', form_error('username')),
              str_replace(array('<p>','</p>'), '', form_error('email')),
            );
          set_flash('danger', array_diff($err, array('')));
          redirect('me');
        }
      }else{

      	//title
	      $judul          = 'Profil Saya';
	      $data['judul']  = $judul;
	      $this->layout->set_title($judul);

	      //breadcrumb/untuk navigasi
	      $this->load->library('breadcrumb');
	      $this->breadcrumb->clear();
	      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
	      $this->breadcrumb->add_crumb($judul);

	      $this->load->model('m_auth');

	      $data['first_name'] = array('name' => 'first_name', 'id' => 'first_name', 'type' => 'text', 'value' => $this->form_validation->set_value('first_name', user_first_name()), 'class' => 'form-control input-sm', 'placeholder' => '');
	      $data['last_name'] = array('name' => 'last_name', 'id' => 'last_name', 'type' => 'text', 'value' => $this->form_validation->set_value('last_name', user_last_name()), 'class' => 'form-control input-sm', 'placeholder' => '');
	      $data['nickname'] = array('name' => 'nickname', 'id' => 'nickname', 'type' => 'text', 'value' => $this->form_validation->set_value('nickname', user_nickname()), 'class' => 'form-control input-sm', 'placeholder' => '');
	      $data['username'] = array('name' => 'username', 'id' => 'username', 'type' => 'text', 'value' => $this->form_validation->set_value('username', user_username()), 'class' => 'form-control input-sm', 'placeholder' => '');
	      $data['email'] = array('name' => 'email', 'id' => 'email', 'type' => 'text', 'value' => $this->form_validation->set_value('email', user_email()), 'class' => 'form-control input-sm', 'placeholder' => '');

      	//menggunakan theme back
      	$this->layout->theme('apotek','auth/me', $data);
      }      
      
    }
  }

  //change password
  function change_password() {    

    if (!$this->ion_auth->logged_in()) {
      set_flash('info', 'Anda belum masuk aplikasi');
      redirect('login', 'refresh');
    }else{

    	if (isset($_POST) && !empty($_POST)) {

    		$this->form_validation->set_rules('old', 'Kata Sandi Sekarang', 'required');
    		$this->form_validation->set_rules('new', 'Kata Sandi Baru', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
    		$this->form_validation->set_rules('new_confirm', 'Konfirmasi Kata Sandi Baru', 'required');

    		if ($this->form_validation->run() == false) {
    			$err  = array(
              str_replace(array('<p>','</p>'), '', form_error('old')),
              str_replace(array('<p>','</p>'), '', form_error('new')),
              str_replace(array('<p>','</p>'), '', form_error('new_confirm')),
            );
          set_flash('danger', array_diff($err, array('')));
          redirect('change_password');
    		}else{
    			$identity = $this->session->userdata('identity');
      		$change = $this->ion_auth->change_password($identity, $this->input->post('old'), $this->input->post('new'));

      		if ($change) {

	        //if the password was successfully changed
	        // set_flash('success', 'Kata Sandi berhasil diperbaharui');
	        redirect('me', 'refresh');
		      } else {
		        // set_flash('danger', 'Kata Sandi gagal diperbaharui');
		        redirect('change_password', 'refresh');
		      }
    		}

    	}else{

    		//title
	      $judul          			= 'Ganti Kata Sandi';
	      $this->data['judul']  = $judul;
	      $this->layout->set_title($judul);

	      //breadcrumb/untuk navigasi
	      $this->load->library('breadcrumb');
	      $this->breadcrumb->clear();
        $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
	      $this->breadcrumb->add_crumb('Profil Saya', site_url('me'));
	      $this->breadcrumb->add_crumb($judul);

    		$this->data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
      	$this->data['old_password'] = array('name' => 'old', 'id' => 'old', 'type' => 'password', 'class' => 'form-control input-sm', 'placeholder' => '');
      	$this->data['new_password'] = array('name' => 'new', 'id' => 'new', 'type' => 'password', 'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$', 'class' => 'form-control input-sm', 'placeholder' => '');
      	$this->data['new_password_confirm'] = array('name' => 'new_confirm', 'id' => 'new_confirm', 'type' => 'password', 'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$', 'class' => 'form-control input-sm', 'placeholder' => '');
      	$this->data['user_id'] = array('name' => 'user_id', 'id' => 'user_id', 'type' => 'hidden', 'value' => user_id());

      	$this->layout->theme('apotek','auth/change_password', $this->data);

    	}

    }
  }

  //log the user in
  function login() {

    if ($this->ion_auth->logged_in()) {
      $this->ion_auth->logout();
    }
    
    if ((isset($_POST) && !empty($_POST))) {

      //validate form input
      $this->form_validation->set_rules('identity', 'ID', 'required');
      $this->form_validation->set_rules('password', 'Kata Sandi', 'required');

      if ($this->form_validation->run() == true) {

        //check to see if the user is logging in
        //check for "remember me"
        $remember = (bool) $this->input->post('remember');

        if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) {

          //if the login is successful
          //redirect them back to the home page
          set_flash('success', 'Berhasil masuk aplikasi');

          //mengambil url sebelum ke halaman login (kecuali halaman logout)
          if (isset($_REQUEST['redirurl']) && $_REQUEST['redirurl'] != site_url('logout') && $_REQUEST['redirurl'] != site_url('login')) {
            $url = $_REQUEST['redirurl'];
          } else {
            if (!$this->ion_auth->in_group(array($this->config->item('super_admin_group', 'ion_auth'), $this->config->item('admin_group', 'ion_auth')))) {
              $url = site_url('dasbor');
            } else {
              $url = site_url('dasbor');
            }
          }

          //dikembalikan ke halaman sebelum mengakses halaman login
          redirect($url, 'refresh');
        } else {

          //if the login was un-successful
          //redirect them back to the login page          
          redirect('login', 'refresh');

          //use redirects instead of loading views for compatibility with MY_Controller libraries
        }
      } else {

        $err  = array(
            str_replace(array('<p>','</p>'), '', form_error('identity')),
            str_replace(array('<p>','</p>'), '', form_error('password')),
          );
        set_flash('danger', array_diff($err, array('')));
        redirect('login', 'refresh');
      }

    }else{

      $this->data['identity'] = array('name' => 'identity', 'id' => 'identity', 'type' => 'text', 'value' => $this->form_validation->set_value('identity'), 'class' => 'form-control', 'placeholder' => 'Nama Pengguna / Email', 'style' => 'border-right:transparent;');
      $this->data['password'] = array('name' => 'password', 'id' => 'password', 'type' => 'password', 'class' => 'form-control', 'placeholder' => 'Kata Sandi', 'style' => 'border-right:transparent;');
      $this->load->view('apotek/layouts/auth/login', $this->data);

    }   
  }

  //log the user out
  function logout() {

    if ($this->ion_auth->logged_in()) {
      //log the user out
      $logout = $this->ion_auth->logout();      
      set_flash('success', 'Berhasil keluar aplikasi');
    }
    //redirect them to the login page
    redirect('login', 'refresh');
  }

  //forgot password
  function forgot_password() {

    //setting validation rules by checking wheather identity is username or email
    if ($this->config->item('identity', 'ion_auth') == 'username') {
      $this->form_validation->set_rules('email', 'Nama Pengguna', 'required');
    } else {
      $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    }

    if ($this->form_validation->run() == false) {

      //setup the input
      $this->data['email'] = array('name' => 'email', 'id' => 'email', 'class' => 'form-control', 'placeholder' => 'Nama Pengguna');

      if ($this->config->item('identity', 'ion_auth') == 'username') {
        $this->data['identity_label'] = 'Nama Pengguna';
      } else {
        $this->data['identity_label'] = 'Email';
      }

      //set any errors and display the form
      $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
      $this->load->view('back/layouts/auth/forgot_password', $this->data);
    } else {

      // get identity from username or email
      if ($this->config->item('identity', 'ion_auth') == 'username') {
        $identity = $this->ion_auth->where('username', strtolower($this->input->post('email')))->users()->row();
      } else {
        $identity = $this->ion_auth->where('email', strtolower($this->input->post('email')))->users()->row();
      }
      if (empty($identity)) {

        if ($this->config->item('identity', 'ion_auth') == 'username') {
          $this->ion_auth->set_message('Nama Pengguna tidak terdaftar');
        } else {
          $this->ion_auth->set_message('Email tidak terdaftar');
        }

        $this->session->set_flashdata('message', $this->ion_auth->messages());
        redirect("auth/forgot_password", 'refresh');
      }

      //run the forgotten password method to email an activation code to the user
      $forgotten = $this->ion_auth->forgotten_password($identity->{$this->config->item('identity', 'ion_auth')});

      if ($forgotten) {

        //if there were no errors
        $this->session->set_flashdata('message', $this->ion_auth->messages());
        redirect("login", 'refresh');

        //we should display a confirmation page here instead of the login page

      } else {
        $this->session->set_flashdata('message', $this->ion_auth->errors());
        redirect("auth/forgot_password", 'refresh');
      }
    }
  }

  //reset password - final step for forgotten password
  public function reset_password($code = NULL) {
    if (!$code) {
      show_404();
    }

    $user = $this->ion_auth->forgotten_password_check($code);

    if ($user) {

      //if the code is valid then display the password reset form

      $this->form_validation->set_rules('new', 'Kata Sandi Baru', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
      $this->form_validation->set_rules('new_confirm', 'Konfirmasi Kata Sandi Baru', 'required');

      if ($this->form_validation->run() == false) {

        //display the form

        //set the flash data error message if there is one
        $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

        $this->data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
        $this->data['new_password'] = array('name' => 'new', 'id' => 'new', 'type' => 'password', 'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$', 'class' => 'form-control', 'placeholder' => 'Kata Sandi baru, minimal ' . $this->data['min_password_length'] . ' karakter');
        $this->data['new_password_confirm'] = array('name' => 'new_confirm', 'id' => 'new_confirm', 'type' => 'password', 'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$', 'class' => 'form-control', 'placeholder' => 'Konfirmasi Kata Sandi');
        $this->data['user_id'] = array('name' => 'user_id', 'id' => 'user_id', 'type' => 'hidden', 'value' => $user->id);
        $this->data['code'] = $code;

        //render
        $this->load->view('back/layouts/auth/reset_password', $this->data);
      } else {

        // do we have a valid request?
        if ($user->id != $this->input->post('user_id')) {

          //something fishy might be up
          $this->ion_auth->clear_forgotten_password_code($code);
          show_404();
        } else {

          // finally change the password
          $identity = $user->{$this->config->item('identity', 'ion_auth')};

          $change = $this->ion_auth->reset_password($identity, $this->input->post('new'));

          if ($change) {

            //if the password was successfully changed
            $this->session->set_flashdata('message', $this->ion_auth->messages());
            $this->logout();
          } else {
            $this->session->set_flashdata('message', $this->ion_auth->errors());
            redirect('auth/reset_password/' . $code, 'refresh');
          }
        }
      }
    } else {

      //if the code is invalid then send them back to the forgot password page
      $this->session->set_flashdata('message', $this->ion_auth->errors());
      redirect("auth/forgot_password", 'refresh');
    }
  }

  public function email_update_check_b($email) {

    //ambil id
    $id = $this->security->xss_clean($this->uri->segment(3));

    //untuk cek username unique update
    $Eparams = array($id, $email);
    $Esql = 'SELECT email FROM ' . $this->tables['users'] . ' WHERE id <> ? AND email = ?';
    $Equery = $this->db->query($Esql, $Eparams);

    if ($Equery->num_rows() > 0) {
      $this->form_validation->set_message('email_update_check_b', 'Email ' . $email . ' telah digunakan, coba ganti yang lain');
      return FALSE;
    } else {
      return TRUE;
    }
  }

  public function username_update_check_b($uname) {

    //ambil id
    $id = $this->security->xss_clean($this->uri->segment(3));

    //untuk cek username unique update
    $Uparams = array($id, $uname);
    $Usql = 'SELECT username FROM ' . $this->tables['users'] . ' WHERE id <> ? AND username = ?';
    $Uquery = $this->db->query($Usql, $Uparams);

    if ($Uquery->num_rows() > 0) {
      $this->form_validation->set_message('username_update_check_b', 'Nama Pengguna ' . $uname . ' telah digunakan, coba ganti yang lain');
      return FALSE;
    } else {
      return TRUE;
    }
  }


  public function email_update_check($email) {

    //ambil data user aktif
    $user = $this->ion_auth->user()->row();

    //untuk cek username unique update
    $Eparams = array($id = $user->id, $email);
    $Esql = 'SELECT email FROM ' . $this->tables['users'] . ' WHERE id != ? AND email = ?';
    $Equery = $this->db->query($Esql, $Eparams);

    if ($Equery->num_rows() > 0) {
      $this->form_validation->set_message('email_update_check', 'Email ' . $email . ' telah digunakan, coba ganti yang lain');
      return FALSE;
    } else {
      return TRUE;
    }
  }

  public function username_update_check($uname) {

    //ambil data user aktif
    $user = $this->ion_auth->user()->row();

    //untuk cek username unique update
    $Uparams = array($id = $user->id, $url = $uname);
    $Usql = 'SELECT username FROM ' . $this->tables['users'] . ' WHERE id != ? AND username = ?';
    $Uquery = $this->db->query($Usql, $Uparams);

    if ($Uquery->num_rows() > 0) {
      $this->form_validation->set_message('username_update_check', 'Nama Pengguna ' . $uname . ' telah digunakan, coba ganti yang lain');
      return FALSE;
    } else {
      return TRUE;
    }
  }

  private function cek_group_id($id){
    if (empty($id))
    {
      return FALSE;
    }

    return $this->db->where('id', $id)
        ->where('name', default_group())
        ->order_by('id', "ASC")
        ->limit(1)
        ->count_all_results($this->tables['groups']) > 0;
  }

}
